package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appId}")
    private String appid;
    @Value("${zzyl.wechat.appSecret}")
    private String secret;

    @Override
    public String getOpenid(String code) {
        //使用hutool HttpUtil
        Map<String,Object> requstParamMap = getAppConfig();
        requstParamMap.put("js_code",code);
        //发起请求
        String result = HttpUtil.get(REQUEST_URL,requstParamMap);
        //字符串转换为json
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断接口是否请求成功
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    /**
     * 封装参数
     * @return
     */
    private Map<String, Object> getAppConfig() {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("appid",appid);
        resultMap.put("secret",secret);
        return resultMap;
    }

    /**
     * 获取手机号
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {

        String token = getToken();

        String url = PHONE_REQUEST_URL + token;

        HashMap<String, Object> param = new HashMap<>();
        param.put("code",phoneCode);

        String result = HttpUtil.post(url, JSONUtil.toJsonStr(param));

        //字符串转换成json
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断是否请求成功
        if(jsonObject.getInt("errcode") != 0){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    public String getToken(){
        Map<String,Object> map = getAppConfig();
        String result = HttpUtil.get(TOKEN_URL,map);
        //字符串转换成json
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断是否请求成功
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}
